from django.contrib import admin

from .models import Question,Choice
from django.db.models import Sum

   
class ChoiceInline(admin.TabularInline):
    model = Choice
    extra = 3
    verbose_name = '选项'  # 原 'Choice'
    verbose_name_plural = '选项'  # 原 'Choices'

class QuestionAdmin(admin.ModelAdmin):
    fieldsets = [
        ('问题信息', {"fields": ["question_text"]}),
        ('发布信息', {"fields": ["pub_date"], "classes": ["collapse"]}),
    ]
    inlines = [ChoiceInline]
    list_display = ["question_text", "pub_date", "was_published_recently","total_votes"]
    list_filter = ["pub_date"]
    search_fields = ["question_text"]

    # 自定义列标题
    def was_published_recently(self, obj):
        return obj.was_published_recently()
    was_published_recently.short_description = ('最近发布')  # 列标题
    was_published_recently.boolean = True
    was_published_recently.admin_order_field = 'pub_date'

    def total_votes(self, obj):
        return obj.choice_set.aggregate(total=Sum('votes'))['total'] or 0
    total_votes.short_description = ('总票数')  # 列标题
    total_votes.admin_order_field = 'choice__votes'  # 指定排序字段

admin.site.register(Question, QuestionAdmin)
admin.site.register(Choice)
admin.site.site_header = '投票管理系统'  # 此处配置的标题会被模板变量引用
admin.site.site_title = '投票系统管理'
admin.site.index_title = '管理首页'
